﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Linq;
using System.Web.UI.WebControls;
namespace IBS.SharePointFoundation.Utilities.Layouts.IBS.SharePointFoundation.Utilities
{
    public partial class MasterPagePicker : LayoutsPageBase
    {
        private enum Scopes
        {
            Web,
            Site
        }

        const string DEFAULTMP = "v4.master";

        protected void Page_Load(object sender, EventArgs e)
        {
            rblScope.SelectedIndexChanged += new EventHandler(rblScope_SelectedIndexChanged);
            btnSubmit.Click += new EventHandler(btnSubmit_Click);
            if(!IsPostBack)
                Initialize();
        }

        void btnSubmit_Click(object sender, EventArgs e)
        {
            if (lbMasterPages.SelectedIndex == -1) return;

            if (cbResetToDefault.Checked) { ResetMasterPage(); }
            else { ApplyMasterPage(); }
        
            Response.Redirect(Request.RawUrl);
        }

        private void ResetMasterPage()
        {
            if (cbApplyToSubsites.Checked)
            {
                //Apply to all subsites
                ResetAllSubsites(SPContext.Current.Web);
            }
            else
            {
                SPContext.Current.Web.MasterUrl = lbMasterPages.SelectedValue;
                SPContext.Current.Web.Update();
            }
        }

        private void ResetAllSubsites(SPWeb sPWeb)
        {
            throw new NotImplementedException();
        }

        private void ApplyMasterPage()
        {
            if (cbApplyToSubsites.Checked)
            {
                //Apply to all subsites
                ApplyToAllSubsites(SPContext.Current.Web);
            }
            else
            {
                SPContext.Current.Web.MasterUrl = lbMasterPages.SelectedValue;
                SPContext.Current.Web.Update();
            }
        }
        private void ApplyToAllSubsites(SPWeb web)
        {
            web.MasterUrl = lbMasterPages.SelectedValue;
            web.Update();

            foreach(SPWeb sWeb in web.Webs)
            {
                ApplyToAllSubsites(sWeb);
            }

        }

        private void Initialize()
        {
            if (SPContext.Current.Web.IsRootWeb) { rblScope.Visible = false; }
            switch (GetCurrentScope())
            {
                case Scopes.Site:
                    PopulateMasterPages("site");
                    rblScope.SelectedIndex = 1;
                    break;
                case Scopes.Web:
                    PopulateMasterPages("web");
                    rblScope.SelectedIndex = 0;
                    break;
            }
            SelectCurrentMasterPage();
        }

        private Scopes GetCurrentScope()
        {
            if (SPContext.Current.Web.MasterUrl.StartsWith("/_catalogs", StringComparison.InvariantCultureIgnoreCase))
                return Scopes.Site;
            else
                return Scopes.Web;
        }

        private void SelectCurrentMasterPage()
        {
            ListItem li = lbMasterPages.Items.FindByValue(SPContext.Current.Web.MasterUrl);
            if (li != null) li.Selected = true;
        }

        void rblScope_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateMasterPages(rblScope.SelectedValue);
            if (rblScope.SelectedValue == GetCurrentScope().ToString().ToLower())
                SelectCurrentMasterPage();
        }

        protected void PopulateMasterPages(string scope)
        {
            lbMasterPages.Items.Clear();
            SPList list;
            if (scope == "site")
                list = SPContext.Current.Site.RootWeb.Lists["Master Page Gallery"];
            else
                list = SPContext.Current.Web.Lists["Master Page Gallery"];
            
            var masterPages = from SPListItem item in list.Items
                              where item.Name.EndsWith(".master")
                              select new { Name = item.Name, Value = item.File.ServerRelativeUrl };

            lbMasterPages.DataSource = masterPages;
            lbMasterPages.DataTextField = "Name";
            lbMasterPages.DataValueField = "Value";
            lbMasterPages.DataBind();

        }
    }
}
